<template>
  <el-card class="performance-container">
    <!-- 顶部过滤区域 -->
    <div class="filter-section">
      <el-date-picker
        v-model="selectedMonth"
        type="month"
        placeholder="选择月份"
        :disabled-date="disabledFutureMonths"
        value-format="YYYY-MM"
        @change="fetchPerformance"
      />
    </div>

    <!-- 顶部统计指标 -->
    <div class="stats-row">
      <el-card shadow="hover" class="stat-card">
        <el-statistic
          title="本月工作量"
          :value="performanceData.workload || 0"
          :precision="0"
        >
          <template #suffix>
            <span class="stat-unit">件</span>
          </template>
        </el-statistic>
        <div class="stat-trend">
          <el-icon :color="workloadTrend >= 0 ? '#67C23A' : '#F56C6C'">
            <ArrowUp v-if="workloadTrend >= 0" />
            <ArrowDown v-else />
          </el-icon>
          <span :class="workloadTrend >= 0 ? 'positive' : 'negative'">
            {{ Math.abs(workloadTrend * 100) }}%
          </span>
          <span class="trend-text">环比上月</span>
        </div>
      </el-card>

      <el-card shadow="hover" class="stat-card">
        <el-statistic
          title="审批通过率"
          :value="performanceData.approvalRate || 0"
          :precision="1"
        >
          <template #suffix>
            <span class="stat-unit">%</span>
          </template>
        </el-statistic>
        <div class="stat-trend">
          <el-icon :color="approvalTrend >= 0 ? '#67C23A' : '#F56C6C'">
            <ArrowUp v-if="approvalTrend >= 0" />
            <ArrowDown v-else />
          </el-icon>
          <span :class="approvalTrend >= 0 ? 'positive' : 'negative'">
            {{ Math.abs(approvalTrend * 100) }}%
          </span>
          <span class="trend-text">环比上月</span>
        </div>
      </el-card>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>数据加载中...</span>
    </div>

    <!-- 图表展示 -->
    <div v-else class="chart-row">
      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="chart-header">
            <span>月度工作量统计</span>
            <el-select
              v-model="timeRange"
              size="small"
              style="width: 120px"
              @change="fetchPerformance"
            >
              <el-option label="近30天" value="30"></el-option>
            </el-select>
          </div>
        </template>
        <div class="chart-wrapper">
          <VChart
            :key="'bar-chart-' + chartKey"
            :option="barChartOptions"
            :autoresize="true"
          />
        </div>
      </el-card>

      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="chart-header">
            <span>审批通过率分布</span>
            <el-radio-group
              v-model="chartView"
              size="small"
              @change="handleChartViewChange"
            >
              <el-radio-button value="pie">饼图</el-radio-button>
              <el-radio-button value="bar">柱状图</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div class="chart-wrapper">
          <VChart
            :key="'pie-chart-' + chartKey"
            :option="currentChartOption"
            :autoresize="true"
          />
        </div>
      </el-card>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { getPerformance } from '@/api/workcontent.js'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, PieChart } from 'echarts/charts'
import { useUserStore } from '@/stores/user'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import dayjs from 'dayjs'

use([
  CanvasRenderer,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 数据状态
const performanceData = ref({
  workload: 0,
  approvalRate: 0,
  trend: {
    workload: 0,
    approvalRate: 0
  }
})

const loading = ref(true)
const timeRange = ref('30')
const chartView = ref('pie')
const selectedMonth = ref(dayjs().format('YYYY-MM'))
const selectedMonth1 = computed(() => {
  return dayjs(selectedMonth.value).subtract(1, 'month').format('YYYY-MM')
})
const chartKey = ref(0)

// 计算属性
const workloadTrend = computed(() => {
  const current = performanceData.value.workload;
  const trendValue = performanceData.value.trend?.workload;

  if (current === 0 && trendValue === 0) return 0;  // 本月和上月都为0 → 0
  if (trendValue === 0) return 1;                   // 上月为0，本月有数据 → 1
  const trend = current / trendValue - 1;
  return parseFloat(trend.toFixed(4));
});

const approvalTrend = computed(() => {
  const current = performanceData.value.approvalRate;
  const trendValue = performanceData.value.trend?.approvalRate;

  if (current === 0 && trendValue === 0) return 0;  // 本月和上月都为0 → 0
  const trend = current / trendValue - 1;
  return parseFloat(trend.toFixed(4));
});

// 图表配置
const barChartOptions = computed(() => ({
  title: {
    text: `${selectedMonth.value} 工作量统计`,
    left: 'center',
    textStyle: {
      fontSize: 14,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: '{b}<br/>{a}: {c} 件'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['工作量'],
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    name: '工作量(件)',
    nameLocation: 'middle',
    nameGap: 25
  },
  series: [
    {
      name: '工作量',
      type: 'bar',
      barWidth: '60%',
      data: [performanceData.value.workload || 0],
      itemStyle: {
        color: '#409EFF',
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c} 件'
      }
    }
  ]
}))

const pieChartOptions = computed(() => ({
  title: {
    text: `${selectedMonth.value} 审批通过率`,
    left: 'center',
    textStyle: {
      fontSize: 14,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a}<br/>{b}: {c}% ({d}%)'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'center',
    data: ['通过', '未通过']
  },
  series: [
    {
      name: '审批通过率',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 5,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}: {c}%'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '14',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: true
      },
      data: [
        { value: performanceData.value.approvalRate || 0, name: '通过' },
        { value: 100 - (performanceData.value.approvalRate || 0), name: '未通过' }
      ],
      color: ['#67C23A', '#F56C6C']
    }
  ]
}))

const barViewOptions = computed(() => ({
  title: {
    text: `${selectedMonth.value} 审批通过率`,
    left: 'center',
    textStyle: {
      fontSize: 14,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: '{b}<br/>{a}: {c}%'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['通过率'],
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    name: '通过率(%)',
    max: 100,
    nameLocation: 'middle',
    nameGap: 25
  },
  series: [
    {
      name: '通过率',
      type: 'bar',
      barWidth: '60%',
      data: [performanceData.value.approvalRate || 0],
      itemStyle: {
        color: '#67C23A',
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}%'
      }
    }
  ]
}))

const currentChartOption = computed(() =>
  chartView.value === 'pie' ? pieChartOptions.value : barViewOptions.value
)

// 方法
const disabledFutureMonths = (time) => {
  return time > new Date()
}

const fetchPerformance = async () => {
  try {
    loading.value = true
    const userId = useUserStore().user.id
    const response = await getPerformance(userId, selectedMonth.value)
    const response1 = await getPerformance(userId,selectedMonth1.value)

      performanceData.value = {

        workload: response.data.data.workload || 0,
        approvalRate: response.data.data.approvalrate || 0,
        trend: {
          workload: response1.data.data.workload || 0,
          approvalRate: response1.data.data.approvalrate || 0
        }
      }

      console.log(performanceData.value);


  } catch (error) {
    console.error('获取绩效数据失败:', error)
    ElMessage.error('获取绩效数据失败，请稍后重试')
  } finally {
    loading.value = false
    chartKey.value++ // 强制图表重新渲染
  }
}

const handleChartViewChange = () => {
  chartKey.value++ // 强制图表重新渲染
}

onMounted(fetchPerformance)
</script>

<style scoped lang="scss">
.performance-container {
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  min-height: 600px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  padding: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.stat-unit {
  font-size: 14px;
  margin-left: 4px;
  color: var(--el-text-color-secondary);
}

.stat-trend {
  display: flex;
  align-items: center;
  margin-top: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);

  .el-icon {
    margin-right: 4px;
  }
}

.positive {
  color: var(--el-color-success);
}

.negative {
  color: var(--el-color-danger);
}

.trend-text {
  margin-left: 4px;
}

.chart-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 16px;
}

.chart-card {
  border-radius: 8px;
  overflow: hidden;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.chart-wrapper {
  height: 300px;
  width: 100%;
}

.loading-overlay {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: var(--el-text-color-secondary);

  .loading-icon {
    font-size: 24px;
    margin-bottom: 8px;
    animation: rotate 2s linear infinite;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .stats-row,
  .chart-row {
    grid-template-columns: 1fr;
  }

  .chart-wrapper {
    height: 250px;
  }

  .filter-section {
    justify-content: flex-start;
  }
}
</style>
